<?php

/**
 *  前台用户控制器
 * @author xiaojy  xiaojy@wanthings.com
 * @copyright 成都网信天成科技有限公司, 2016, http://www.wanthings.com
 */
class UserInfoController extends Controller
{
    public function actionDetail()
    {
        $sid = Yii::app()->user->getId();//
        if (empty($sid)) {
            $this->showError('请先登录');
        }
        $result = UserInfo::model()->getBySid($sid);
        if ($result['errno'] == 0) {
            $data = $result['result'];
        } else {
            $data = array();
        }
        //获取客户端ip.
        $ip = Yii::app()->request->getUserHostAddress();
        //echo Yii::app()->request->getUserHostAddress(); 

        if (Yii::app()->request->isPostRequest) {
            $user = Yii::app()->request->getPost('user');
            
            $user['sid'] = $sid;
            $user['last_login_ip'] = $ip;
            if (!empty($data)) {
                $re = UserInfo::model()->updateUserInfo($user);
            } else {
                $re = UserInfo::model()->add($user);
            }
            if ($re['errno'] == 0) {
                $this->showSuccess('修改成功', $this->createUrl('/userinfo/detail'));
            } else {
                $this->showError('修改失败' . $re['errmsg'], $this->referer);
            }
        }

        $this->render('detail', compact('data'));
    }

    public function actionIndex()
    {
        
        $this->render('index');
    }


    public function actionHome()
    {
        $this->render('home');
    }

    //ajax上传
    public function actionUpload()
    {
        $bhv = new FilesComponent;
        $upfile = $bhv->upload('file');
        if (!$upfile) {
            $result['error'] = $bhv->error;
        } else {
            $result = $upfile;
        }
        echo CJSON::encode($result);
    }

    public function actionUploadavatar()
    {
        if (!empty($this->user_id)) {
            $result['errno'] = 1;
            $result['errmsg'] = '更新失败';
            return $result;
        }
        $bhv = new FilesComponent;
        $upfile = $bhv->upload('file');
        if (!$upfile) {
            $result['error'] = $bhv->error;
        } else {

            $hash = $upfile['hash'];
            $path = $bhv->getFilePath($hash);
            $size = getimagesize($path);
            $user['sid'] = $this->user_id;

            $user['avatar'] = $hash;
            $user_info = UserInfo::model()->updateUserInfo($user);
            if ($user_info['errno'] == 0) {
                $result['errno'] = 0;
                $result['result'] = WxUtil::getGoodsImgUrl($hash);
                $result['size'] = $size;
            } else {
                $result['errno'] = 1;
                $result['errmsg'] = '更新失败';
            }
        }
        echo CJSON::encode($result);
    }


}
